package com.useeinfo.oa.modules.maintaining.biz;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.extend.biz.CrudBiz;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.func.lang.StringUtils;
import com.useeinfo.framework.sugar.tools.DateTimeUtils;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.biz.DictInfoBiz;
import com.useeinfo.oa.modules.base.biz.FacilityCatBiz;
import com.useeinfo.oa.modules.base.entity.*;
import com.useeinfo.oa.modules.base.vo.MaintainDataVO;
import com.useeinfo.oa.modules.base.vo.MaintainTechnologyVO;
import com.useeinfo.oa.modules.maintaining.dao.MaintainTechnologyDao;
import com.useeinfo.oa.modules.maintaining.entity.MaintainData;
import com.useeinfo.oa.modules.maintaining.entity.MaintainTechnology;
import com.useeinfo.oa.modules.maintaining.enums.InputTypeEnum;
import com.useeinfo.oa.modules.security.biz.OrganizationBiz;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Auther: 陈炜
 * @Date: 2018/12/28 13:00
 */
@Service
public class MaintainTechnologyBiz extends CrudBiz<MaintainTechnologyDao, MaintainTechnology> {


    @Autowired
    private OrganizationBiz organizationBiz;

    @Autowired
    private FacilityCatBiz facilityCatBiz;

    @Autowired
    private DictInfoBiz dictInfoBiz;

    @Autowired
    private MaintainDataBiz maintainDataBiz;
    /**
     * 获取维修单编号
     *
     * @param enterpriseId
     * @return
     */
    public String getCode(String enterpriseId) {
        String code = enterpriseId + "-" + DateTimeUtils.formatDateToStringWithOnlyDate(new Date(), "yyyyMMdd") + "-" + (int) ((Math.random() * 9 + 1) * 100000);
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("code", code);
        List<MaintainTechnology> maintainTechnologyList = this.findList(queryParam);
        if (CollectionUtils.isNotEmpty(maintainTechnologyList)) {
            return getCode(enterpriseId);
        } else {
            return code;
        }
    }


    private Sheet sheet;
    private Sheet sheet1;
    private Row row;
    private Row row1;

    public ResultDto checkData(Workbook wb,Enterprise enterprise){
        String enterpriseId = StringConverters.null2String(enterprise.getId());
        if (wb == null) {
            return ResultUtil.error("Workbook对象为空！");
        }
        sheet = wb.getSheetAt(0);
        sheet1 = wb.getSheetAt(1);
        // 得到总行数
        int rowNum = sheet.getLastRowNum();
        int rowNum1 = sheet1.getLastRowNum();
        JSONArray result = new JSONArray();
        JSONObject jsonObject;
        for (int i = 1; i <= rowNum; i++) {
            row = sheet.getRow(i);
            if (StringUtils.isBlank(StringConverters.null2String(getCellFormatValue(row.getCell(0))))) {
                jsonObject = new JSONObject();
                jsonObject.put("msg", "Excel数据sheet1第" + (i + 1) + "行，保养临时编号存在问题，请确认后重新提交");
                result.add(jsonObject);
            }

            if (StringUtils.isBlank(StringConverters.null2String(getCellFormatValue(row.getCell(1))))) {
                jsonObject = new JSONObject();
                jsonObject.put("msg", "Excel数据sheet1第" + (i + 1) + "行，保养名称存在问题，请确认后重新提交");
                result.add(jsonObject);
            }

            String tOrganization = StringConverters.null2String(getCellFormatValue(row.getCell(2)));
            if(StringUtils.isBlank(tOrganization)){
                jsonObject = new JSONObject();
                jsonObject.put("msg", "Excel数据sheet1第" + (i + 1) + "行，所属部门存在问题，请确认后重新提交");
                result.add(jsonObject);
            }else{
                QueryParam queryParam = new QueryParam();
                queryParam.getSqlMap().put("enterpriseId",enterpriseId);
                queryParam.getSqlMap().put("organizationName",tOrganization);
                if(CollectionUtils.isEmpty(organizationBiz.findList(queryParam))){
                    jsonObject = new JSONObject();
                    jsonObject.put("msg", "Excel数据sheet1第" + (i + 1) + "行，所属部门存在问题，请确认后重新提交");
                    result.add(jsonObject);
                }
            }

            String tFacilityMajor = StringConverters.null2String(getCellFormatValue(row.getCell(3)));
            String tFacilityCat = StringConverters.null2String(getCellFormatValue(row.getCell(4)));
            if (StringUtils.isNotBlank(tFacilityMajor) && StringUtils.isNotBlank(tFacilityCat) ) {
                QueryParam bigCatParam = new QueryParam();
                bigCatParam.getSqlMap().put("enterpriseId",enterpriseId);
                bigCatParam.getSqlMap().put("catName",tFacilityMajor);
                bigCatParam.getSqlMap().put("bigParent",tOrganization);
                List<FacilityCat> rootCats = facilityCatBiz.findList(bigCatParam);
                QueryParam catParam = new QueryParam();
                catParam.getSqlMap().put("enterpriseId",enterpriseId);
                catParam.getSqlMap().put("catName",tFacilityCat);
                catParam.getSqlMap().put("notBigParent",tOrganization);
                List<FacilityCat> cats = facilityCatBiz.findList(catParam);
                if(CollectionUtils.isEmpty(rootCats) || CollectionUtils.isEmpty(cats)){
                    jsonObject = new JSONObject();
                    jsonObject.put("msg", "Excel数据sheet1第" + (i + 1) + "行，所属专业和所属分类存在问题，请确认后重新提交");
                    result.add(jsonObject);
                }
            }
        }

        for(int i = 1;i <= rowNum1;i++){
            row1 = sheet1.getRow(i);
            if (StringUtils.isBlank(StringConverters.null2String(getCellFormatValue(row1.getCell(0))))) {
                jsonObject = new JSONObject();
                jsonObject.put("msg", "Excel数据sheet2第" + (i + 1) + "行，内容临时编号存在问题，请确认后重新提交");
                result.add(jsonObject);
            }

            if (StringUtils.isBlank(StringConverters.null2String(getCellFormatValue(row1.getCell(1))))) {
                jsonObject = new JSONObject();
                jsonObject.put("msg", "Excel数据sheet2第" + (i + 1) + "行，维保项目存在问题，请确认后重新提交");
                result.add(jsonObject);
            }

            if (StringUtils.isBlank(StringConverters.null2String(getCellFormatValue(row1.getCell(2))))) {
                jsonObject = new JSONObject();
                jsonObject.put("msg", "Excel数据sheet2第" + (i + 1) + "行，维保类别存在问题，请确认后重新提交");
                result.add(jsonObject);
            }

            String dApplicationScenarios = StringConverters.null2String(getCellFormatValue(row1.getCell(3)));
            if (StringUtils.isBlank(StringConverters.null2String(getCellFormatValue(row1.getCell(3))))) {
                jsonObject = new JSONObject();
                jsonObject.put("msg", "Excel数据sheet2第" + (i + 1) + "行，应用场景存在问题，请确认后重新提交");
                result.add(jsonObject);
            }else{
                QueryParam dictParam = new QueryParam();
                dictParam.getSqlMap().put("enterpriseId",enterpriseId);
                dictParam.getSqlMap().put("propertyName",dApplicationScenarios);
                List<DictInfo> dictInfos = dictInfoBiz.findList(dictParam);
                if(CollectionUtils.isEmpty(dictInfos)){
                    jsonObject = new JSONObject();
                    jsonObject.put("msg", "Excel数据sheet2第" + (i + 1) + "行，应用场景存在问题，请确认后重新提交");
                    result.add(jsonObject);
                }
            }

            String dInputTypeEnum = StringConverters.null2String(getCellFormatValue(row1.getCell(4)));
            InputTypeEnum typeEnum = InputTypeEnum.getEnum(dInputTypeEnum);
            if(StringUtils.isBlank(dInputTypeEnum)){
                jsonObject = new JSONObject();
                jsonObject.put("msg", "Excel数据sheet2第" + (i + 1) + "行，输入类型存在问题，请确认后重新提交");
                result.add(jsonObject);
            }else{
                if(typeEnum == null){
                    jsonObject = new JSONObject();
                    jsonObject.put("msg", "Excel数据sheet2第" + (i + 1) + "行，输入类型存在问题，请确认后重新提交");
                    result.add(jsonObject);
                }else{
                    if(InputTypeEnum.NUMBER.getCode().equals(typeEnum.getCode())){
                        String dMaxNumber = StringConverters.null2String(getCellFormatValue(row1.getCell(5)));
                        String dMinNumber = StringConverters.null2String(getCellFormatValue(row1.getCell(6)));
                        if(StringUtils.isBlank(dMaxNumber) || StringUtils.isBlank(dMinNumber)){
                            jsonObject = new JSONObject();
                            jsonObject.put("msg", "Excel数据sheet2第" + (i + 1) + "行，最大值和最小值存在问题，请确认后重新提交");
                            result.add(jsonObject);
                        }
                    }
                }
            }

            String dPhoto = StringConverters.null2String(getCellFormatValue(row1.getCell(8)));
            if(StringUtils.isBlank(dPhoto)){
                jsonObject = new JSONObject();
                jsonObject.put("msg", "Excel数据sheet2第" + (i + 1) + "行，是否拍照存在问题，请确认后重新提交");
                result.add(jsonObject);
            }else{
                if("是".equals(dPhoto) || "否".equals(dPhoto)){

                }else{
                    jsonObject = new JSONObject();
                    jsonObject.put("msg", "Excel数据sheet2第" + (i + 1) + "行，是否拍照存在问题，请确认后重新提交");
                    result.add(jsonObject);
                }
            }
        }
        if (result.size() > 0) {
            ResultDto resultDto = new ResultDto();
            resultDto.setStatus(1);
            resultDto.setData(result);
            resultDto.setMsg("导入失败");
            return resultDto;
        }
        return ResultUtil.success();
    }


    public synchronized ResultDto importTechnology(Workbook wb, Enterprise enterprise) {
        if (wb == null) {
            return ResultUtil.error("Workbook对象为空！");
        }
        sheet = wb.getSheetAt(0);
        sheet1 = wb.getSheetAt(1);
        // 得到总行数
        int rowNum = sheet.getLastRowNum();
        int rowNum1 = sheet1.getLastRowNum();
        String enterpriseId = StringConverters.null2String(enterprise.getId());
        List<MaintainTechnologyVO> maintainTechnologyVOS = new ArrayList<>();
        List<MaintainDataVO> maintainDataVOS = new ArrayList<>();
        for (int i = 1; i <= rowNum; i++) {
            row = sheet.getRow(i);
            String tCode = StringConverters.null2String(getCellFormatValue(row.getCell(0)));
            String tName = StringConverters.null2String(getCellFormatValue(row.getCell(1)));
            String tOrganization = StringConverters.null2String(getCellFormatValue(row.getCell(2)));
            String tFacilityMajor = StringConverters.null2String(getCellFormatValue(row.getCell(3)));
            String tFacilityCat = StringConverters.null2String(getCellFormatValue(row.getCell(4)));
            String tEstimateTime = StringConverters.null2String(getCellFormatValue(row.getCell(5)));
            String tRequireSkill = StringConverters.null2String(getCellFormatValue(row.getCell(6)));
            String tSafetyRequirement = StringConverters.null2String(getCellFormatValue(row.getCell(7)));
            String tRequireMaterials = StringConverters.null2String(getCellFormatValue(row.getCell(8)));
            String tRequireTools = StringConverters.null2String(getCellFormatValue(row.getCell(9)));
            String tPrepareWork = StringConverters.null2String(getCellFormatValue(row.getCell(10)));
            String tDescription = StringConverters.null2String(getCellFormatValue(row.getCell(11)));


            if(StringUtils.isNotBlank(tCode) && StringUtils.isNotBlank(tName) && StringUtils.isNotBlank(tOrganization)){
                QueryParam queryParam = new QueryParam();
                queryParam.getSqlMap().put("enterpriseId",enterpriseId);
                queryParam.getSqlMap().put("organizationName",tOrganization);
                List<Organization> organizations = organizationBiz.findList(queryParam);

                QueryParam bigCatParam = new QueryParam();
                bigCatParam.getSqlMap().put("enterpriseId",enterpriseId);
                bigCatParam.getSqlMap().put("catName",tFacilityMajor);
                bigCatParam.getSqlMap().put("bigParent",tOrganization);
                List<FacilityCat> rootCats = facilityCatBiz.findList(bigCatParam);
                QueryParam catParam = new QueryParam();
                catParam.getSqlMap().put("enterpriseId",enterpriseId);
                catParam.getSqlMap().put("catName",tFacilityCat);
                catParam.getSqlMap().put("notBigParent",tOrganization);
                List<FacilityCat> cats = facilityCatBiz.findList(catParam);
                if(CollectionUtils.isNotEmpty(organizations) && CollectionUtils.isNotEmpty(rootCats) && CollectionUtils.isNotEmpty(cats)){
                    MaintainTechnologyVO maintainTechnologyVO = new MaintainTechnologyVO();
                    maintainTechnologyVO.setCode(tCode);
                    maintainTechnologyVO.setName(tName);
                    maintainTechnologyVO.setEstimateTime(tEstimateTime);
                    maintainTechnologyVO.setDescription(tDescription);
                    maintainTechnologyVO.setPrepareWork(tPrepareWork);
                    if(StringUtils.isNotBlank(tFacilityCat)){
                        maintainTechnologyVO.setFacilityCat(StringConverters.null2String(cats.get(0).getId()));
                    }
                    maintainTechnologyVO.setRequireMaterials(tRequireMaterials);
                    maintainTechnologyVO.setRequireTools(tRequireTools);
                    maintainTechnologyVO.setRequireSkill(tRequireSkill);
                    maintainTechnologyVO.setOrganization(StringConverters.null2String(organizations.get(0).getId()));
                    maintainTechnologyVO.setSafetyRequirement(tSafetyRequirement);
                    maintainTechnologyVO.setDescription(tDescription);
                    maintainTechnologyVOS.add(maintainTechnologyVO);
                }
            }
        }

        for (int i = 1; i <= rowNum1; i++) {
            row1 = sheet1.getRow(i);
            String dCode = StringConverters.null2String(getCellFormatValue(row1.getCell(0)));
            String dName = StringConverters.null2String(getCellFormatValue(row1.getCell(1)));
            String dCategory = StringConverters.null2String(getCellFormatValue(row1.getCell(2)));
            String dApplicationScenarios = StringConverters.null2String(getCellFormatValue(row1.getCell(3)));
            String dInputTypeEnum = StringConverters.null2String(getCellFormatValue(row1.getCell(4)));
            String dMaxNumber = StringConverters.null2String(getCellFormatValue(row1.getCell(5)));
            String dMinNumber = StringConverters.null2String(getCellFormatValue(row1.getCell(6)));
            String dUnit = StringConverters.null2String(getCellFormatValue(row1.getCell(7)));
            String dPhoto = StringConverters.null2String(getCellFormatValue(row1.getCell(8)));

            if(StringUtils.isNotBlank(dCode) && StringUtils.isNotBlank(dName) && StringUtils.isNotBlank(dCategory) && StringUtils.isNotBlank(dApplicationScenarios) && StringUtils.isNotBlank(dInputTypeEnum)){
                QueryParam dictParam = new QueryParam();
                dictParam.getSqlMap().put("enterpriseId",enterpriseId);
                dictParam.getSqlMap().put("propertyName",dApplicationScenarios);
                List<DictInfo> dictInfos = dictInfoBiz.findList(dictParam);
                InputTypeEnum typeEnum = InputTypeEnum.getEnum(dInputTypeEnum);
                if(CollectionUtils.isNotEmpty(dictInfos) && typeEnum != null && ("是".equals(dPhoto) || "否".equals(dPhoto))){
                    MaintainDataVO maintainDataVO = new MaintainDataVO();
                    maintainDataVO.setDictInfo(StringConverters.null2String(dictInfos.get(0).getId()));
                    maintainDataVO.setInputTypeEnum(dInputTypeEnum);
                    maintainDataVO.setUnit(dUnit);
                    maintainDataVO.setCode(dCode);
                    maintainDataVO.setName(dName);
                    maintainDataVO.setCategory(dCategory);
                    if("是".equals(dPhoto)){
                        maintainDataVO.setPhoto("true");
                    }else{
                        maintainDataVO.setPhoto("false");
                    }
                    if(InputTypeEnum.NUMBER.getCode().equals(typeEnum.getCode())){
                        maintainDataVO.setMaxNumber(dMaxNumber);
                        maintainDataVO.setMinNumber(dMinNumber);
                    }
                    maintainDataVOS.add(maintainDataVO);
                }
            }
        }
        for(MaintainTechnologyVO maintainTechnologyVO : maintainTechnologyVOS){
            List<MaintainDataVO> dataList = new ArrayList<>();
            String tCode = maintainTechnologyVO.getCode();
            for(MaintainDataVO maintainDataVO : maintainDataVOS){
                if(tCode.equals(maintainDataVO.getCode())){
                    dataList.add(maintainDataVO);
                }
            }

            if(CollectionUtils.isNotEmpty(dataList)){
                MaintainTechnology maintainTechnology = new MaintainTechnology();
                maintainTechnology.setEnterprise(enterprise);
                maintainTechnology.setFacilityCat(facilityCatBiz.findModel(StringConverters.null2Long(maintainTechnologyVO.getFacilityCat())));
                maintainTechnology.setOrganization(organizationBiz.findModel(StringConverters.null2Long(maintainTechnologyVO.getOrganization())));
                maintainTechnology.setCode(getCode(enterprise.getId()+""));
                maintainTechnology.setDescription(maintainTechnologyVO.getDescription());
                maintainTechnology.setEstimateTime(maintainTechnologyVO.getEstimateTime());
                maintainTechnology.setSafetyRequirement(maintainTechnologyVO.getSafetyRequirement());
                maintainTechnology.setName(maintainTechnologyVO.getName());
                maintainTechnology.setPrepareWork(maintainTechnology.getPrepareWork());
                maintainTechnology.setRequireSkill(maintainTechnology.getRequireSkill());
                maintainTechnology.setRequireTools(maintainTechnology.getRequireTools());
                maintainTechnology.setRequireMaterials(maintainTechnology.getRequireMaterials());
                addOrUpdate(maintainTechnology);

                JSONArray dataArray = new JSONArray();
                for(MaintainDataVO maintainDataVO:dataList){
                    MaintainData maintainData = new MaintainData();
                    maintainData.setMaintainTechnology(maintainTechnology);
                    maintainData.setName(maintainDataVO.getName());
                    maintainData.setEnterprise(enterprise);
                    if("数字".equals(maintainDataVO.getInputTypeEnum())){
                        maintainData.setMaxNumber(StringConverters.null2Double(maintainDataVO.getMaxNumber()));
                        maintainData.setMinNumber(StringConverters.null2Double(maintainDataVO.getMinNumber()));
                    }
                    maintainData.setInputTypeEnum(InputTypeEnum.getEnum(maintainDataVO.getInputTypeEnum()));
                    maintainData.setCategory(maintainDataVO.getCategory());
                    maintainData.setDictInfo(dictInfoBiz.findModel(StringConverters.null2Long(maintainDataVO.getDictInfo())));
                    maintainData.setPhoto(StringConverters.null2Boolean(maintainDataVO.getPhoto()));
                    maintainDataBiz.addOrUpdate(maintainData);
                    dataArray.add(maintainData.toJSONObject2());
                }
                maintainTechnology.setMaintainDataContent(dataArray.toString());
            }
        }
        return ResultUtil.success();
    }


    /**
     * 根据Cell类型设置数据
     *
     * @param cell
     * @return
     * @author zengwendong
     */
    private Object getCellFormatValue(Cell cell) {
        Object cellvalue = "";
        if (cell != null) {
            // 判断当前Cell的Type
            switch (cell.getCellType()) {
                case Cell.CELL_TYPE_NUMERIC:// 如果当前Cell的Type为NUMERIC
                case Cell.CELL_TYPE_FORMULA: {
                    // 判断当前的cell是否为Date
                    if (DateUtil.isCellDateFormatted(cell)) {
                        // 如果是Date类型则，转化为Data格式
                        // data格式是带时分秒的：2013-7-10 0:00:00
                        // cellvalue = cell.getDateCellValue().toLocaleString();
                        // data格式是不带带时分秒的：2013-7-10
                        Date date = cell.getDateCellValue();
                        cellvalue = date;
                    } else {// 如果是纯数字

                        // 取得当前Cell的数值
                        DecimalFormat dfs = new DecimalFormat("0");

                        cellvalue = dfs.format(cell.getNumericCellValue());
                    }
                    break;
                }
                case Cell.CELL_TYPE_STRING:// 如果当前Cell的Type为STRING
                    // 取得当前的Cell字符串
                    cellvalue = cell.getRichStringCellValue().getString();
                    break;
                default:// 默认的Cell值
                    cellvalue = "";
            }
        } else {
            cellvalue = "";
        }
        return cellvalue;
    }
}
